package com.cnpc.iot.scgl.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cnpc.framework.base.dao.RedisDao;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.service.BaseService;
import com.cnpc.framework.utils.StrUtil;
import com.cnpc.iot.scgl.entity.Batch;
import com.cnpc.iot.scgl.utils.QrcodeUtils;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.zxing.WriterException;

/**
 * 批次管理控制器
 * 
 * @author jrn 2018-03-18 23:08:59由代码生成器自动生成
 */
@Controller
@RequestMapping("/batch")
public class BatchController {
	public static final String NZM_REDIS_KEY = "nzm_key";
	@Resource
	private BaseService baseService;
	@Resource
	private RedisDao redisDao;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "iot/scgl/batch_list";
	}
	
	@RequestMapping(value = "/getBatchByPorId/{proId}", method = RequestMethod.POST)
	@ResponseBody
	public List<Batch> getBatchByPorId(@PathVariable("proId") String proId) {
		return baseService.find("from Batch where proId='" + proId + "'");
	}
	
	@RequestMapping(value = "/getBatchByPorIds/{proId}", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject getBatchByPor(@PathVariable("proId") String proId, String callbackparam) {
		List<Batch> batchs = baseService.find("from Batch where proId='" + proId + "'");
		return new JSONPObject(callbackparam, batchs);
	}

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(String id, String produce, HttpServletRequest request) {
		if (StringUtils.isEmpty(id)) {
			request.setAttribute("proId", produce);
		} else {
			Batch batch = baseService.get(Batch.class, id);
			request.setAttribute("proId", batch.getProId());
		}
		request.setAttribute("id", id);
		return "iot/scgl/batch_edit";
	}

	@RequestMapping(value = "/bindFlow", method = RequestMethod.GET)
	public String bindFlow(String id, HttpServletRequest request) {
		request.setAttribute("id", id);
		return "iot/scgl/batch_flow";
	}

	@RequestMapping(value = "save_flow_bind")
	@ResponseBody
	public Result saveFlow(String id, String proName) {
		System.out.println(id);
		Batch batch = baseService.get(Batch.class, id);
		batch.setProName(proName);
		baseService.update(batch);
		return new Result(true);
	}

	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public String detail(String id, HttpServletRequest request) {
		request.setAttribute("id", id);
		return "iot/scgl/batch_detail";
	}

	@RequestMapping(value = "/get/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Batch get(@PathVariable("id") String id) {
		return baseService.get(Batch.class, id);
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public Result save(Batch batch) {
		if (StrUtil.isEmpty(batch.getId())) {
			baseService.save(batch);
		} else {
			batch.setUpdateDateTime(new Date());
			baseService.update(batch);
		}
		return new Result(true);
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Result delete(@PathVariable("id") String id) {
		Batch batch = this.get(id);
		try {
			baseService.delete(batch);
			return new Result();
		} catch (Exception e) {
			return new Result(false, "该数据已经被引用，不可删除");
		}
	}
	
	@RequestMapping(value = "/showQrcode", method = RequestMethod.GET)
	public String showQrcode(String batchId, HttpServletRequest request) {
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
		+ request.getContextPath();
		String qrcode = QrcodeUtils.creatRrCode(basePath+"/mobile/main/"+batchId+"/1111", 200, 200);
		request.setAttribute("qrcode", qrcode);
		request.setAttribute("batchId", batchId);
		return "iot/scgl/show_qrcode";
	}
	
	@RequestMapping(value = "/downloadQrcode", method = RequestMethod.POST)
	public void downloadAllQr(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			String bathchId) throws WriterException, IOException {
		httpServletResponse.setContentType("application/zip");
		httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + bathchId + ".zip");
		String basePath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort()
		+ httpServletRequest.getContextPath();
		OutputStream outputStream = httpServletResponse.getOutputStream();
		ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
		Batch batch = baseService.get(Batch.class, bathchId);
		int pcnum = Integer.parseInt(batch.getPcNum());
		List<String> nzmList = new ArrayList<String>();
		for (int i=1; i<pcnum+1; i++) {
			Double random = Math.random();
			String str = random.toString().substring(2, 12);
			BufferedImage buffImg = QrcodeUtils.getBufferedImage(basePath+"/mobile/main/"+bathchId+"/"+i, 200, 200);
			ZipEntry entry = new ZipEntry(batch.getPcName()+"_" + str + ".png");
			zipOutputStream.putNextEntry(entry);
			ImageIO.write(buffImg, "png", zipOutputStream);
			zipOutputStream.flush();
			nzmList.add(str);
		}
		List<String> nzm = redisDao.get(NZM_REDIS_KEY, List.class);
		if(null == nzm) {
			redisDao.save(NZM_REDIS_KEY, nzmList);
		}else {
			nzmList.addAll(nzm);
			redisDao.save(NZM_REDIS_KEY, nzmList);
		}
		zipOutputStream.close();
		outputStream.flush();
		outputStream.close();
	}
	
	
	public static void main(String[] args) {
		Double random = Math.random();
		String str = random.toString().substring(2, 12);
		System.out.println(str);
	}

}
